package com.example.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.example.config.listener.ReadUserListener;
import com.example.entity.ComplexHeadData;
import com.example.entity.TUser;
import com.example.mapper.TUserMapper;
import com.example.service.UserService;
import com.example.util.JWTUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser tUser = tUserMapper.selectByLoginAct(username);

//        判断用户是否为空，若不为空，则将其具有的权限添加进去
        if (tUser == null) {
            throw new UsernameNotFoundException("登录账号名不能为空！");
        }

        return tUser;
    }

    @Override
    public PageInfo<TUser> loadUserByPage(Integer current, Integer pageSize) {
        PageHelper.startPage(current, pageSize);
        List<TUser> tUsers = tUserMapper.loadUserByPage();
        PageInfo<TUser> tUserPageInfo = new PageInfo<>(tUsers);
        return tUserPageInfo;
    }

    @Override
    public int editUser(TUser tUser,String Authorization) {
        TUser loginUser = JWTUtils.parseUserFromJWT(Authorization);
        Integer IdFromEditUser = loginUser.getId();
        tUser.setEditBy(IdFromEditUser);
        tUser.setEditTime(new Date());
        if (StringUtils.hasText(tUser.getPassword())) {
            String encodedPwd = passwordEncoder.encode(tUser.getLoginPwd());
            tUser.setLoginPwd(encodedPwd);
        }
        int row = tUserMapper.editUserByPrimaryKey(tUser);
        return row;
    }

    @Override
    public int addUser(TUser tUser, String Authorization) {
//        设置创建时间
        tUser.setCreateTime(new Date());
//        设置创建人
        TUser tUserJWT = JWTUtils.parseUserFromJWT(Authorization);
        Integer idFromCreateByUser = tUserJWT.getId();
        tUser.setCreateBy(idFromCreateByUser);
//        对前端传过来的密码进行加密
        String loginPwd = tUser.getPassword();
        if(StringUtils.hasText(tUser.getPassword())) {
            String encodedPwd = passwordEncoder.encode(loginPwd);
            tUser.setLoginPwd(encodedPwd);
        }
        int row = tUserMapper.addUserInfo(tUser);
        return row;
    }

    @Override
    public TUser loadUserByUserId(Integer id) {
        TUser tUser = tUserMapper.loadUserByUserId(id);
        if (ObjectUtils.isEmpty(tUser.getCreateByDo())) {
            tUser.setCreateByDo(new TUser());
        }
        if (ObjectUtils.isEmpty(tUser.getEditByDo())) {
            tUser.setEditByDo(new TUser());
        }
        return tUser;
    }

    @Override
    public int delUserInfoById(int id) {
        int row = tUserMapper.deleteByPrimaryKey(id);
        return row;
    }

    @Override
    public int batchDelUserInfo(List<String> idList) {
        int row = tUserMapper.batchDelUserInfo(idList);
        return row;
    }

    @Override
    public void uploadExcel(InputStream inputStream) {
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        EasyExcel.read(inputStream, TUser.class, new ReadUserListener(tUserMapper)).sheet().doRead();
    }

    @Override
    public void downTemplate(String isTemplate) {
        String fileName = "D:\\dlyk\\dlyk_0930\\用户模板.xlsx";
        String excelName = "模板";
        List<TUser> userData = ListUtils.newArrayList();
//        如果为true，则表示下载模板，否则表示导出数据
        if (isTemplate.equals("false")) {
            userData = tUserMapper.loadUserByPage();
            excelName = "用户数据";
            fileName = "D:\\dlyk\\dlyk_0930\\用户数据.xlsx";
        }

//        ArrayList<ComplexHeadData> testTemplate = ListUtils.newArrayList();
//        ComplexHeadData complexHeadData = new ComplexHeadData();
//        complexHeadData.setDoubleData(3.2);
//        complexHeadData.setDate(new Date());
//        complexHeadData.setString("测试数据");
//        testTemplate.add(complexHeadData);
//        当模板中，只有一个sheet时
        EasyExcel.write(fileName, TUser.class).sheet(excelName).doWrite(userData);

        // 当模板中，有多个sheet时
//        try (ExcelWriter excelWriter = EasyExcel.write(fileName, TUser.class).build()) {
//            // 去调用写入,这里我调用了五次，实际使用时根据数据库分页的总的页数来。这里最终会写到5个sheet里面
//            for (int i = 0; i < 3; i++) {
//                // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样
//                WriteSheet writeSheet = EasyExcel.writerSheet(i, "模板" + i).build();
//                // 分页去数据库查询数据 这里可以去数据库查询每一页的数据
////                List<TUser> data = data();
//                if (i == 1) {
//                    excelWriter.write(testTemplate, writeSheet);
//                }else {
//                    excelWriter.write(userTemplate, writeSheet);
//                }
//            }
//        }

    }
}
